package db_main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/messages/im"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
)

func GetPrivateChatSessionList(param map[string]interface{}, order string, page, size int, groupBy string) ([]*models_main.PrivateChatSession, error) {
	fName := "GetPrivateChatSessionList"
	o := make([]*models_main.PrivateChatSession, 0)
	table := mysql.GetRTable(&models_main.PrivateChatSession{})
	param["is_deleted"] = false
	mysql.Condition(table, param, groupBy, order, page, size)
	err := table.Find(&o).Error
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func DefaultChatAdmin() []*im.Conversation {
	o := make([]*im.Conversation, 0)
	o = append(o, &im.Conversation{
		UserId:   global.Config.GetString("official.anchor1.uid"),
		AnchorId: global.Config.GetString("official.anchor1.uid"),
	})
	o = append(o, &im.Conversation{
		UserId:   global.Config.GetString("official.anchor2.uid"),
		AnchorId: global.Config.GetString("official.anchor2.uid"),
	})
	return o
}

func GetPrivateChatSession(param map[string]interface{}) (*models_main.PrivateChatSession, error) {
	fName := "GetPrivateChatSession"
	o := &models_main.PrivateChatSession{}
	table := mysql.GetRTable(&models_main.PrivateChatSession{})
	_, ok := param["is_deleted"]
	if !ok {
		param["is_deleted"] = false
	}
	mysql.Condition(table, param, "", "id desc", 0, 0)
	err := table.Take(o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return o, nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func InsertPrivateChatSession(chatSession *models_main.PrivateChatSession) error {
	fName := "InsertPrivateChatSession"
	err := global.GetX().Create(chatSession).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func UpdatePrivateChatSession(columns []string, chatSession *models_main.PrivateChatSession) error {
	fName := "UpdatePrivateChatSession"
	err := global.GetX().
		Model(chatSession).
		Select(columns).
		Updates(chatSession).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func DeletePrivateChatSessions(chatSessions []*models_main.PrivateChatSession) error {
	fName := "DeletePrivateChatSessions"
	var ids []int
	for _, v := range chatSessions {
		ids = append(ids, v.Id)
	}
	err := global.GetX().
		Model(&models_main.PrivateChatSession{}).
		Where("id in ?", ids).
		Updates(map[string]interface{}{
			"is_deleted": true,
			"status":     models_main.PrivateChatSessionStatusEnd,
		}).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func GetPrivateChatHistoryList(param map[string]interface{}) ([]models_main.PrivateChatHistory, error) {
	fName := "GetPrivateChatHistoryList"
	o := []models_main.PrivateChatHistory{}
	table := mysql.GetRTable(&models_main.PrivateChatHistory{})
	mysql.Condition(table, param, "", "id DESC", 0, 0)
	err := table.Find(&o).Error
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func GetPrivateChatHistory(anchorId int, liveId int64) (*models_main.PrivateChatHistory, error) {
	fName := "GetPrivateChatHistoryList"
	o := &models_main.PrivateChatHistory{}
	err := mysql.GetRTable(&models_main.PrivateChatHistory{}).
		Where("anchor_id = ? and live_id = ? "+
			"and start_time <= now() and (end_time >= now() or end_time = 0 or end_time is null)", anchorId, liveId).
		Take(o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func GetPrivateChatHistoryById(id int) (*models_main.PrivateChatHistory, error) {
	fName := "GetPrivateChatHistoryList"
	o := &models_main.PrivateChatHistory{}
	err := mysql.GetRTable(&models_main.PrivateChatHistory{}).
		Take(o, id).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func InsertPrivateChatHistory(history *models_main.PrivateChatHistory) error {
	fName := "InsertPrivateChatHistory"
	err := global.GetX().Create(history).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func UpdatePrivateChatHistory(columns []string, history *models_main.PrivateChatHistory) error {
	fName := "UpdatePrivateChatHistory"
	err := global.GetX().
		Model(history).
		Select(columns).
		Updates(history).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func UpdatePrivateChatHistoryEndTime() error {
	fName := "UpdatePrivateChatHistoryEndTime"
	historys := []models_main.PrivateChatHistory{}
	err := global.GetR().Select("t.*").
		Table("main.db_private_chat_history t").
		Joins("LEFT JOIN live.db_live_history t1 ON live_id = t1.liveid").
		Where("t.live_id > 0 AND t1.start_stamp > 0 AND (t.end_time = 0 OR t.end_time IS NULL)").Find(&historys).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}

	hIds := []int{}
	for _, v := range historys {
		hIds = append(hIds, v.Id)
	}

	if len(hIds) <= 0 {
		return nil
	}

	sql := `
UPDATE main.db_private_chat_history t
LEFT JOIN
    models_live.db_live_history t1 ON t.live_id = t1.liveid and t.anchor_id = t1.anchorid 
SET 
    t.end_time = IFNULL(FROM_UNIXTIME(t1.end_stamp), "0000-00-00 00:00:00")
WHERE
    t.id in ? and 
	t1.start_stamp = unix_timestamp(t.start_time)
`
	err = global.GetX().Exec(sql, hIds).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}
